// Default empty project template
#include "MESBBJH.hpp"

#include <bb/cascades/Application>
#include <bb/cascades/QmlDocument>
#include <bb/cascades/AbstractPane>
#include <QFile>
#include <qtextstream.h>
#include <qfile.h>

using namespace bb::cascades;

MESBBJH::MESBBJH(bb::cascades::Application *app) :
		QObject(app) {
	// create scene document from main.qml asset
	// set parent to created document to ensure it exists for the whole application lifetime
	QmlDocument *qml = QmlDocument::create("asset:///main.qml").parent(this);
	qml->setContextProperty("_app", this);
	// create root object for the UI
	root = qml->createRootObject<AbstractPane>();
	// set created root object as a scene
	app->setScene(root);

	// Create seed for the random
	// That is needed only once on application startup
	QTime time = QTime::currentTime();
	qsrand((uint) time.msec());

	index = 0;
	containerNow = 0;
	interval = 100;
	nowTime = 0;
	score = 0;
//	createTempData();
}

void MESBBJH::pushMainGame() {
	index = 0;
	score = 0;
	nowTime = 0;
	containerNow = 0;

	createTempData();
	createLayout();
	createTimer();
	addTouchHandler();
	showLog("finish push screen");
}

void MESBBJH::createTempData() {
	QString name;
	switch (indextMusic) {
	case 0:
		name = "n.txt";
		break;
	case 1:
		name = "n.txt";
		break;
	default:
		name = "n.txt";
		break;
	}

	QString appFolder(QDir::homePath());
	appFolder.chop(4);
	QString originalFileName = appFolder + "app/native/assets/sounds/" + name;
	QFile file(originalFileName);
	file.open(QIODevice::ReadOnly);
	QString s(file.readAll());
	showLog(s);
	processRlC(s);
//	for (int i = 0; i < mLyricItems; i += 10) {
//		gamePlayList.append(new ShowText("Show", i));
//		gamePlayList.append(new ShowText("me", i + 1));
//		gamePlayList.append(new ShowText("the", i + 2));
//		gamePlayList.append(new ShowText("meaning", i + 3));
//		gamePlayList.append(new ShowText("of", i + 4));
//		gamePlayList.append(new ShowText("being", i + 5));
//		gamePlayList.append(new ShowText("lonely", i + 6));
//		gamePlayList.append(new ShowText("Show", i + 7));
//		gamePlayList.append(new ShowText("me", i + 8));
//		gamePlayList.append(new ShowText("the", i + 9));
//	}
}

void MESBBJH::processRlC(QString s) {
	char c = 10;
	QStringList splitD = s.split(c);
	fprintf(stdout,"%s\n","Length:"+splitD.length());
	fflush(stdout);
	QList<lyricItem> mListLyricItem;
	for (int i = 0; i < splitD.length(); ++i) {
		QString text = splitD.at(i);
		int timeR = text.lastIndexOf("]");
		QString content = text.right(text.length() - timeR - 1);

		int indext = text.indexOf("[");
		while (indext >= 0) {
			int timeL = indext;
			int timeR = text.indexOf("]", indext);
			if (timeL >= 0 && timeL < timeR) {
				QString sTime = text.mid(timeL + 1, timeR - timeL - 1);
				int phut = sTime.mid(0, 2).toInt();
				int giay = sTime.mid(3, 2).toInt();
				int milis = sTime.mid(6, 2).toInt();
				lyricItem item;
				item.timeStart = phut * 60 * 60 + giay * 60 + milis * 100 / 60;
				item.content = content;
				mListLyricItem.append(item);
			}
			indext = text.indexOf("[", indext + 1);
		}
	}
	mLyricItems = new lyricItem[mListLyricItem.length()];
	for (int i = 0; i < mListLyricItem.length(); ++i) {
		mLyricItems[i] = mListLyricItem.at(i);
	}
	//SapXep
	for (int i = 0; i < mListLyricItem.length() - 1; ++i) {
		int min = i;
		for (int j = i + 1; j < mListLyricItem.length(); ++j) {
			if (mLyricItems[min].timeStart > mLyricItems[j].timeStart) {
				min = j;
			} else if (mLyricItems[min].timeStart == mLyricItems[j].timeStart
					&& mLyricItems[min].content.length()
							< mLyricItems[j].content.length()) {
				min = j;
			}
		}
		if (min != i) {
			lyricItem temp = mLyricItems[i];
			mLyricItems[i] = mLyricItems[min];
			mLyricItems[min] = temp;

//			temp.timeStart = mLyricItems[i].timeStart;
//			temp.content = mLyricItems[i].content;
//
//			mLyricItems[i].timeStart = mLyricItems[min].timeStart;
//			mLyricItems[i].content = mLyricItems[min].content;
//
//			mLyricItems[min].timeStart = temp.timeStart;
//			mLyricItems[min].content = temp.content;
		}
	}
	for (int i = 0; i < mListLyricItem.length(); ++i) {
		QString temp("TimeStart:");
		temp += QString::number(mLyricItems[i].timeStart) + " # "
				+ mLyricItems[i].content;
		fprintf(stdout,"%s\n",temp.toUtf8().constData());
		fflush(stdout);
		long lTemp = mLyricItems[i].timeStart;
		QString contentTemp = mLyricItems[i].content;
//		gamePlayList[i]->text = contentTemp;
//		gamePlayList[i]->time = lTemp;
	}
	lenghtItem=mListLyricItem.length();
}

void MESBBJH::addTouchHandler() {
	Container *contentContainer = root->findChild<Container*>("content");
	/*contentContainer->addTouchBehavior(
	 TouchBehavior::create()
	 .addTouchReaction(TouchType::Down,
	 PropagationPhase::Capturing,
	 TouchResponse::StartTracking));*/
	connect(contentContainer, SIGNAL(touch(bb::cascades::TouchEvent*)), this,
			SLOT(showLog("hgfhjgjhgj")));
	/*connect(contentContainer,
	 SIGNAL(touch(bb::cascades::TouchEvent*)),
	 this, SLOT(showLog("hgfhjgjhgj")));*/
}

void MESBBJH::createLayout() {
	//Container *contentContainer = root->findChild<Container*>("c6");

	//cList = (Container**)malloc(sizeof(Container*));

	cList.append(root->findChild<Container*>("c0"));
	cList.append(root->findChild<Container*>("c1"));
	cList.append(root->findChild<Container*>("c2"));
	cList.append(root->findChild<Container*>("c3"));
	cList.append(root->findChild<Container*>("c4"));
	cList.append(root->findChild<Container*>("c5"));

	showLog("here");
	//textList = (ShowText*)malloc(sizeof(ShowText));
	showLog("here 1");
	textList.append(new ShowText("Show", 1));
	textList.append(new ShowText("me", 1));
	textList.append(new ShowText("the", 3));
	textList.append(new ShowText("meaning", 5));
	textList.append(new ShowText("of", 7));
	textList.append(new ShowText("being", 9));
	textList.append(new ShowText("lonely", 11));

	/*for (int i = 0 ; i < cList.length(); i++) {
	 Container *c = cList[i];
	 Label *lbl = c->findChild<Label*>("lbl");
	 QString text = textList[i]->text;
	 lbl->setText(text);
	 }*/
}

void MESBBJH::createTimer() {
	timer = new QTimer(this);
	connect(timer, SIGNAL(timeout()), this, SLOT(update()));
	timer->start(interval);
}

void MESBBJH::showLog(QString msg) {
	fprintf(stdout,"%s\n",msg.toUtf8().constData());
	fflush(stdout);
}

void MESBBJH::changeText(int x, int y) {
	showLog(QString::number(x) + "abcdsaf" + QString::number(y));
}

void MESBBJH::handleTouch(int x, int y) {
	for (int i = 0; i < cList.length(); i++) {
		AbsoluteLayoutProperties *layout = cList[i]->findChild<
				AbsoluteLayoutProperties*>();
		int containerX = layout->positionX();
		int containerY = layout->positionY();
		int containerW = cList[i]->preferredWidth();
		int containerH = cList[i]->preferredHeight();

		//showLog(QString::number(containerX) + "Y:" + QString::number(containerY) + "W:" + QString::number(containerW) + "H:" + QString::number(containerH));
		if (x > containerX && x < containerX + containerW && y > containerY
				&& y < containerY + containerH) {
			setTextForContainer("", i);

			if (mLyricItems[index - 1].success != true) {
				mLyricItems[index - 1].success = true;
				score += 1;
				Container *container = root->findChild<Container*>(
						"scoreContainer");
				if (container) {
					Label *lbl = container->findChild<Label*>("scoreLbl");
					showLog("found container");
					if (lbl) {
						showLog("found lbl");
						QString text = QString::number(score);
//					showLog("found container s", text);
						lbl->setText(text);
					}
				}
				break;
			}
		}
	}
}

void MESBBJH::shakeForFail(int index) {
	Container *c = cList[index];
//	AbsoluteLayoutProperties *layout = cList[index]->findChild<
//			AbsoluteLayoutProperties*>();
//	int containerX = layout->positionX();
//
//	ParallelAnimation* buttonOneAnimation =
//			ParallelAnimation::create(c).add(
//					TranslateTransition::create().toX(containerX + 20).duration(
//							2000)).add(
//					FadeTransition::create().to(0.2).duration(
//							2000));

	//c->setBackground(Color::fromRGBA(1,0,0,1));
}

void MESBBJH::update() {
	nowTime += interval;
	if (index == lenghtItem) {
		timer->stop();
		return;
	}
	if (mLyricItems[index].timeStart <= nowTime) {
		QString text = mLyricItems[index].content;
		findOtherContainer();

		setTextForContainer(text, containerNow);

		if (mLyricItems[index].success == false) {
//			showLog("shake for fail");
			shakeForFail(containerNow);
		}

		index++;
	}
}

void MESBBJH::setTextForContainer(QString text, int cIndex) {
	Container *c = cList[cIndex];
	Label *lbl = c->findChild<Label*>("lbl");
	lbl->setText(text);

//	if (text.compare("") != 0) {
//		ImageView *img = c->findChild<ImageView*>("img");
//		if (img) {
//			img->setI
//		}
//	}
}

void MESBBJH::findOtherContainer() {
	int now = containerNow;

	do {
		// Get random value between 0-100
		containerNow = randInt(0, cList.length() - 1);
	} while (containerNow == now);
}

int MESBBJH::randInt(int low, int high) {
	// Random number between low and high
	return qrand() % ((high + 1) - low) + low;
}

/**
 * Ham goi ra khi co su kien tu QML goi ve
 */
void MESBBJH::loadListMusic(QString offset) {
//	if (linkTitle.length() == 0) {
//		QNetworkRequest request = QNetworkRequest();
//		request.setUrl(QUrl("http://123.30.133.183/jamhack/baihat.php"));
//		mNetworkAccessManager->get(request);
//	} else {
	linkTitle.append("file1");
	linkTitle.append("file2");
	linkTitle.append("file3");
	if (offset.length() == 0) {
		indextMusic = 0;
	} else {
		int iOff = offset.toInt();
		indextMusic += iOff;
		if (indextMusic < 0)
			indextMusic = linkTitle.length() - 1;
		else if (indextMusic >= linkTitle.length())
			indextMusic = 0;
	}
	Label* titleMusic = root->findChild<Label*>("titleMusic");
	titleMusic->setText(linkTitle.at(indextMusic));
//	}
}
